package algorithm.leetcode.medium;

/*
 给定一个字符串，逐个翻转字符串中的每个单词。
 */

/**
 * @author jack.wu
 * @version 1.0
 * @date 2020/12/8
 */
public class Question151 {

    public static void main(String[] args) {
        String s = "hello word";
        Question151 question = new Question151();
        String reverseStr = question.reverseWords(s);
        System.out.println(reverseStr);
    }

    public String reverseWords(String s) {
        if (s == null || s.length() < 2) {
            return s;
        }

        s = s.trim();
        StringBuilder sb = new StringBuilder();
        char[] chars = s.toCharArray();
        for (int i = chars.length - 1; i >= 0; i--) {
            if (chars[i] != ' ') {
                int left = i - 1;
                // 找到这个完整的单词
                while (left >= 0 && chars[left] != ' ') {
                    left--;
                }
                // 放入结果中
                for (int j = left + 1; j <= i; j++) {
                    sb.append(chars[j]);
                }
                sb.append(' ');
                // 继续找下个单词
                i = left;
            }
        }
        return sb.toString().trim();
    }

}
